package com.myfoon.view.application;

import com.myfoon.view.context.helper.LocaleHelper;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;


public class LocaleBean {
    private Locale currentLocale;
    private boolean rightToLeft;
    
    public LocaleBean() {
        rightToLeft = false;
    }

    public List<SelectItem> getLocaleItems() {
        FacesContext context = FacesContext.getCurrentInstance();
        Application application = context.getApplication();
        ResourceBundle bundle =
            application.getResourceBundle(context, "messages");

        List<SelectItem> locales = new ArrayList<SelectItem>();
        for (Iterator<Locale> iterator = application.getSupportedLocales();
             iterator.hasNext(); ) {
            Locale locale = iterator.next();

            String language = locale.getLanguage();
            if (language != null) {
                language = language.toLowerCase();
            }

            String country = locale.getCountry();
            if (country != null) {
                country = country.toUpperCase();
            }
            
            if (country != null && !country.equalsIgnoreCase("")) 
            {
            locales.add(new SelectItem(locale,
                                       bundle.getString("lang." + language +
                                                        "_" + country)));
            }
            else {
            locales.add(new SelectItem(locale,
                                       bundle.getString("lang." + language)));
            }
                    
        }

        return locales;
    }
    
    public void valueChange(ValueChangeEvent event) {
        FacesContext context = FacesContext.getCurrentInstance();
        String currentView = context.getViewRoot().getViewId();
        
        this.setCurrentLocale((Locale)event.getNewValue());                    
        context.getViewRoot().setLocale((Locale)event.getNewValue());        
                
        rightToLeft = Boolean.valueOf(LocaleHelper.getValue("global.right-to-left"));        
        
        ViewHandler vh = context.getApplication().getViewHandler();
        UIViewRoot x = vh.createView(context, currentView);
        context.setViewRoot(x);                
    }

    public void setCurrentLocale(Locale currentLocale) {
        this.currentLocale = currentLocale;
    }

    public Locale getCurrentLocale() {
        return currentLocale;
    }

    public void setRightToLeft(boolean rightToLeft) {
        this.rightToLeft = rightToLeft;
    }

    public boolean isRightToLeft() {
        return rightToLeft;
    }
}
